package com.sang.web;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.sang.fegin.UserFeignApi;
import com.sang.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
@RequestMapping("consumer")
public class ConsumerController {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    UserFeignApi userFeignApi;
    /**
     * 关闭service层   直接请求http://localhost:80/consumer/{id}
     * 会调用名为findUserFallBack降级函数
     * @param id
     * @return
     */
    @GetMapping("{id}")     //基于hystrix实现降级回调   HystrixCommand调用的是本类中重写的方法
    @HystrixCommand(fallbackMethod = "findUserFallBack")
    public User queryById(@PathVariable("id") String id){

//        List<ServiceInstance> instances = discoveryClient.getInstances("user-service");  // 大小写都可以
//        ServiceInstance serviceInstance = instances.get(0);
//
//        String host = serviceInstance.getHost();  // 获取主机地址
//        int port = serviceInstance.getPort();     // 获取端口
//        String url = serviceInstance.getUri().toString(); // 获取请求URL
//
//        // String url = "http://localhost:8081/user/" + id;
//        // 调用RestTemplate的getForObject方法，指定url地址和返回值类型
//        Map user = restTemplate.getForObject(url+"/user/"+id, Map.class);
//        return user;

//        String url = "http://user-service/user/"+id;
//        User user = restTemplate.getForObject(url, User.class);

        return userFeignApi.queryById(id);
    }

    /**
     * 降级回调函数     回调函数需要符合预期且可以被后续函数处理
     * @param username
     * @return   固定值  符合预期可被处理
     */
    public User findUserFallBack( String username) {
        User user = new User();
        user.setUsername(username);
        user.setName("这里表示调用了降级处理函数,暂停相关服务");
        return user;
    }


}